package com.feidian.helper.ui.view;

/**
 * @Author WangCheng
 * @version 1.0
 * @category 2015.9.20 15:57
 * @category 自定义组件，用于下拉刷新，上拉加载
 */

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;


import com.feidian.helper.R;

import java.text.SimpleDateFormat;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.feidian.helper.R;

public class XListView extends ListView implements OnScrollListener {

	private static final String TAG = "RefreshListView";
	private int firstVisibleItemPosition; // ??????????????item??????
	private int lastVisibleItemPosition;
	private int downY; // ?????y????????
	private int headerViewHeight; // ????????
	private View headerView; // ?????????

	private final int DOWN_PULL_REFRESH = 0; // ?????????
	private final int RELEASE_REFRESH = 1; // ??????
	private final int REFRESHING = 2; // ?????????
	private final int LOAD_PULL_REFRESH = 3;
	private final int LOAD_RELEASE_REFRESH = 4;
	private final int LOADING = 5;

	private int headerCurrentState = DOWN_PULL_REFRESH; // ????????: ???????????
	private int footerCurrentState = LOAD_PULL_REFRESH;

	private Animation upAnimation; 
	private Animation downAnimation;

	private ImageView ivArrow; // ????????
	private ProgressBar mProgressBar; // ???????????
	private TextView tvState; // ????????
	private TextView tvLastUpdateTime; // ???????????????
	private TextView footerTvState;
	private ProgressBar footerProgressBar;

	private OnRefreshListener mOnRefershListener;
	private boolean isScrollToBottom; // ??????????
	private View footerView; // ?????????
	private int footerViewHeight; // ????????
	private boolean isLoadingMore = false; // ???????????????
	
	public XListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initHeaderView();
		initFooterView();
		this.setOnScrollListener(this);
	}


	private void initFooterView() {
		footerView = View.inflate(getContext(), R.layout.listview_footer, null);
		footerView.measure(0, 0);
		footerViewHeight = footerView.getMeasuredHeight();
		footerView.setPadding(0, 0, 0, -footerViewHeight);
		footerTvState = (TextView) footerView.findViewById(R.id.load_tv_state);
		footerProgressBar = (ProgressBar) footerView
				.findViewById(R.id.load_progressbar);
		this.addFooterView(footerView);
	}

	/**
	 * ??????????
	 */
	private void initHeaderView() {
		headerView = View.inflate(getContext(), R.layout.listview_header, null);
		ivArrow = (ImageView) headerView
				.findViewById(R.id.iv_listview_header_arrow);
		mProgressBar = (ProgressBar) headerView
				.findViewById(R.id.pb_listview_header);
		tvState = (TextView) headerView
				.findViewById(R.id.tv_listview_header_state);
		tvLastUpdateTime = (TextView) headerView
				.findViewById(R.id.tv_listview_header_last_update_time);

		tvLastUpdateTime.setText("上次刷新时间: " + getLastUpdateTime());

		headerView.measure(0, 0);
		headerViewHeight = headerView.getMeasuredHeight();
		headerView.setPadding(0, -headerViewHeight, 0, 0);
		this.addHeaderView(headerView); // ??ListView???????????view????
		initAnimation();
	}
	
	private String getLastUpdateTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(System.currentTimeMillis());
	}

	
	private void initAnimation() {
		upAnimation = new RotateAnimation(0f, -180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		upAnimation.setDuration(500);
		upAnimation.setFillAfter(true);

		downAnimation = new RotateAnimation(-180f, -360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		downAnimation.setDuration(500);
		downAnimation.setFillAfter(true); 
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			downY = (int) ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			
			int moveY = (int) ev.getY();
			int diff;
			
			if(firstVisibleItemPosition == 0){
				if(moveY > downY){
					diff = (moveY - downY)/2;
					int paddingTop = -headerViewHeight + diff;
					if(paddingTop > 0 && headerCurrentState == DOWN_PULL_REFRESH){
						headerCurrentState = RELEASE_REFRESH;
						refreshHeaderView();
					}else if(paddingTop < 0 && headerCurrentState == RELEASE_REFRESH){
						headerCurrentState = DOWN_PULL_REFRESH;
						refreshHeaderView();
					}
					headerView.setPadding(0, paddingTop,0,0);
				}
			}
			
			if(lastVisibleItemPosition == this.getCount() - 1){
				if(downY > moveY){
				    diff = (downY - moveY)/4;
				    int paddingBottom = -footerViewHeight + diff;
				    if(paddingBottom >= 0){
				    	footerCurrentState = LOAD_RELEASE_REFRESH;
				    }else{
				    	footerCurrentState = LOAD_PULL_REFRESH;
				    }
				    footerView.setPadding(0, 0, 0, paddingBottom);
				}
			}
			
				
			
			break;
		case MotionEvent.ACTION_UP:
			if (headerCurrentState == RELEASE_REFRESH) {
				headerView.setPadding(0, 0, 0, 0);
				headerCurrentState = REFRESHING;
				refreshHeaderView();
				if (mOnRefershListener != null) {
					mOnRefershListener.onDownPullRefresh();
				}
			} else if (headerCurrentState == DOWN_PULL_REFRESH) {
				headerView.setPadding(0, -headerViewHeight, 0, 0);
			}
/////////////////////////////////////////////////////////////////////////////
			if (footerCurrentState == LOAD_PULL_REFRESH) {
				footerView.setPadding(0, 0, 0, -footerViewHeight);
			} else if (footerCurrentState == LOAD_RELEASE_REFRESH) {
				footerView.setPadding(0, 0, 0, 0);
				footerCurrentState = LOADING;
				loadFooterView();
				if (mOnRefershListener != null) {
					mOnRefershListener.onLoadingMore();
				}
			}
			break;
		default:
			break;
		}
		return super.onTouchEvent(ev);
	}
	
	private void loadFooterView() {
		switch (footerCurrentState) {
		case LOAD_PULL_REFRESH:
			footerTvState.setText("上拉加载更多... ");
			break;
		case LOAD_RELEASE_REFRESH:
			break;
		case LOADING:
			footerTvState.setText("正在加载...");
			footerProgressBar.setVisibility(View.VISIBLE);
			this.setEnabled(false);
			break;
		default:
			break;
		}
	}


	
	private void refreshHeaderView() {
		switch (headerCurrentState) {
		case DOWN_PULL_REFRESH:
			tvState.setText("下拉以刷新");
			ivArrow.startAnimation(downAnimation);
			break;
		case RELEASE_REFRESH:
			tvState.setText("释放以刷新");
			ivArrow.startAnimation(upAnimation);
			break;
		case REFRESHING:
			ivArrow.clearAnimation();
			ivArrow.setVisibility(View.GONE);
			mProgressBar.setVisibility(View.VISIBLE);
			tvState.setText("正在刷新");
			this.setEnabled(false);
			break;
		default:
			break;
		}
	}
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
        /*
		if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_FLING) {
		
			if (isScrollToBottom && !isLoadingMore) {
				isLoadingMore = true;
				footerView.setPadding(0, 0, 0, 0);
				this.setEnabled(false);
				this.setSelection(this.getCount());

				if (mOnRefershListener != null) {
					mOnRefershListener.onLoadingMore();
				}
			}
		}
		*/
	}
 	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		firstVisibleItemPosition = firstVisibleItem;
		firstVisibleItemPosition = firstVisibleItem;
		lastVisibleItemPosition = getLastVisiblePosition();
		if (getLastVisiblePosition() == (totalItemCount - 1)) {
			isScrollToBottom = isBottom();
		} else {
			isScrollToBottom = isBottom();
		}
	}

	protected boolean isBottom() {
        //XListViewAdapter adapter1 = (XListViewAdapter)mListView.getAdapter();

        if (this.getAdapter() == null || this.getAdapter().isEmpty()) {
            return true;
        }

        final int lastItemPosition = this.getAdapter().getCount() - 1;
        final int lastVisiblePosition = this.getLastVisiblePosition();

       
        if (lastVisiblePosition >= lastItemPosition - 1) {
            final int childIndex = lastVisiblePosition - this.getFirstVisiblePosition();
            final int childCount = this.getChildCount();
            final int index = Math.min(childIndex, childCount - 1);
            final View lastVisibleChild = this.getChildAt(index);
            if (lastVisibleChild != null) {
                return lastVisibleChild.getBottom() <= this.getBottom();
            }
        }

        return false;
    }
	
	public void setOnRefreshListener(OnRefreshListener listener) {
		mOnRefershListener = listener;
	}

	
	public void hideHeaderView() {
		headerView.setPadding(0, -headerViewHeight, 0, 0);
		ivArrow.setVisibility(View.VISIBLE);
		mProgressBar.setVisibility(View.GONE);
		tvState.setText("下拉以刷新");
		tvLastUpdateTime.setText("上次更新时间: " + getLastUpdateTime());
		headerCurrentState = DOWN_PULL_REFRESH;
	}

	public void hideFooterView() {
		footerView.setPadding(0, -footerViewHeight, 0, 0);
		footerProgressBar.setVisibility(View.GONE);
		footerCurrentState = LOAD_PULL_REFRESH;
		footerTvState.setText("上拉加载...");

		isLoadingMore = false;
	}
}

